<?php
/**
 * Created by .
 * User: luogan
 * Date: 2022/1/13
 */

namespace app\exception;

use think\exception\Handle;
use think\exception\HttpException;
use think\facade\Log;
use think\Response;
use Throwable;
use Exception;
use app\constant\CodeConst;
class ExceptionHandle extends Handle
{
    private $code;
    private $msg;
    private $errorCode;

    public function render($request, Throwable $e): Response
    {
        if ($e instanceof BaseException) //自定义异常
        {

            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;

        }else if($e instanceof HttpException) {//http异常
            //排除接口文档auth验证
            if (hash_equals($request->baseUrl(),'/apidoc/apiData')){
                return parent::render($request, $e);
            }
            $this->code = CodeConst::NOT_FOUND_ERROR;
            $this->msg = CodeConst::NOT_FOUND_ERROR_MSG;
            $this->errorCode = CodeConst::NOT_FOUND_ERROR;

        }else{
            // 如果是服务器未处理的异常，将http状态码设置为500，并记录日志
            if(env('app_debug', 'false')){
                return parent::render($request, $e);
            }
            $this->code = CodeConst::SERVER_ERROR;
            $this->msg = '服务器错误';
            $this->errorCode = 500;
            $this->recordErrorLog($e);
        }

        $result = [
            'message'  => $this->msg,
            'code' => $this->errorCode,
            'time' => date('Y-m-d H:i:s',time()),
            'request_url' => $request->url(),
            //'data' =>[],
        ];
        return json($result, 200);

    }

    private function recordErrorLog(Exception $e)
    {
        Log::record($e->getMessage(),'error');
    }
}
